package com.asia5b.a5mall.middleware.logic.viewmodel.member

import androidx.lifecycle.MutableLiveData
import com.asia5b.a5bmall.resource.R
import com.asia5b.a5bmall.resource.ResString
import com.asia5b.a5mall.middleware.base.SimpleViewModel
import com.asia5b.a5mall.middleware.config.UserRepository
import com.asia5b.a5mall.middleware.model.member.MemberModel
import com.asia5b.a5mall.middleware.utils.showMessage
import io.reactivex.functions.Consumer
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody
import java.io.File

/**
 * Created by zhangyuncai on 2019/12/30.
 * 个人信息
 */
class PersonInfoActivityVM :SimpleViewModel() {


    fun editMember(member: MemberModel) {
        var regionId: Int? = member.getRegionId()
        if (regionId == null || regionId <= 0) {
            regionId = null
        }
        val observable = memberApi.editMemberInfo(member.nikename, regionId, member.sex, member.birthday, member.address, member.email, member.tel, member.face)
        baseSubscribe(observable, Consumer { result ->
            UserRepository.updateUserInfo()
            showMessage(ResString.get(R.string.保存成功))
//            providerView().editMemberResult()
            editMemberResultLiveData.value=true
        })
    }
    val editMemberResultLiveData=MutableLiveData<Boolean>()

    /**
     * 将图片资料上传至云服务器
     */
    fun uploader(filePath: String) {
        val localFile = File(filePath)
        val localRequestBody = RequestBody.create("image/jpeg".toMediaTypeOrNull(), localFile)
        val localPart = MultipartBody.Part.createFormData("file", localFile.name, localRequestBody)
        val observable = baseApi.uploader(localPart, "")
                .map { uploadImgResModel ->
                    return@map uploadImgResModel.url
                }
                .flatMap {newFace->
                   val  member = UserRepository.getUserInfo()
                    var regionId: Int? = member.getRegionId()
                    if (regionId == null || regionId <= 0) {
                        regionId = null
                    }
                    memberApi.editMemberInfo(member.nikename, regionId, member.sex, member.birthday, member.address, member.email, member.tel, newFace)
                }
        baseSubscribe(observable, Consumer { member ->
            UserRepository.updateUserInfo()
            showMessage(ResString.get(R.string.修改成功))
//            callback.callback(member.face)
            uploaderLiveData.value=member.face
        })
    }

    val uploaderLiveData=MutableLiveData<String>()
}